package com.dormitory.javadormitory.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CaptchaController {

    //获取验证码
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        // 创建验证码对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);
        String code = captcha.getCode(); // 获取验证码文本内容

        // 将验证码文本内容保存到session中
        HttpSession session = request.getSession();
        session.setAttribute("captcha", code);
        System.out.println("1："+session.getId());

        // 设置响应的类型为图片
        response.setContentType("image/jpeg");

        // 将验证码图片写入响应的输出流
        captcha.write(response.getOutputStream());

        response.getOutputStream().close();
    }
}
